package com.cjie.service.impl;

import com.cjie.domain.ResponseResult;
import com.cjie.domain.entity.LoginUser;
import com.cjie.domain.entity.User;
import com.cjie.domain.vo.BlogUserLoginVo;
import com.cjie.domain.vo.UserInfoVo;
import com.cjie.service.BlogLoginService;
import com.cjie.service.UserService;
import com.cjie.utils.BeanCopyUtils;
import com.cjie.utils.JwtUtil;
import com.cjie.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
public class BlogLoginServiceImpl implements BlogLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    /**
     * 用户登录接口
     *
     * @param user
     * @return
     */
    @Override
    public ResponseResult login(User user) {
        // 调用授权认证
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        // 判断认证是否通过
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        // 获取userid 生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        // 将用户信息存入redis(userId和loginUser中相关权限信息)
        redisCache.setCacheObject("bloglogin:"+userId,loginUser);
        // 把token和userinfo封装返回
        // 将user转换为userinfovo
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUsername(), UserInfoVo.class);
        BlogUserLoginVo blogUserLoginVo = new BlogUserLoginVo(jwt,userInfoVo);
        return ResponseResult.okResult(blogUserLoginVo);
    }
}
